package com.zhilianbao.leyaogo.ui.activity.me.setting;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bql.utils.CheckUtils;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.api.PayApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.ui.activity.base.BaseOkHttpActivity;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.me.PasswordInputView;
import com.zhilianbao.leyaogo.view.widgets.DelayButton;

import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class SetPwdActivity extends BaseOkHttpActivity {

    @BindView(R.id.phone_check)
    LinearLayout mPhoneCheck;
    @BindView(R.id.next_step)
    TextView mNextStep;
    @BindView(R.id.set_new_pwd)
    LinearLayout mSetNewPwd;
    @BindView(R.id.again_new_pwd)
    LinearLayout mAgainNewPwd;
    @BindView(R.id.input_pwd)
    PasswordInputView mInputPwd;
    @BindView(R.id.again_pwd)
    PasswordInputView mAgainPwd;
    @BindView(R.id.commit)
    TextView mCommit;
    @BindView(R.id.tv_set_info)
    TextView mSetInfo;
    @BindView(R.id.get_check_num)
    DelayButton mGetCheckNum;
    @BindView(R.id.tv_phone_num)
    EditText mTvPhoneNum;
    @BindView(R.id.et_pwd_check_num)
    EditText mEtPwdCheckNum;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.activity_set_pwd;
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        initToolbar(getString(R.string.set_pay_pwd));
        mTvPhoneNum.addTextChangedListener(verifyTextWatcher);
        mEtPwdCheckNum.addTextChangedListener(verifyTextWatcher);
        mInputPwd.addTextChangedListener(pwdTextWatcher);
        mAgainPwd.addTextChangedListener(pwdTextWatcher);
        mSetInfo.setText(getString(R.string.verify_phone));
        mNextStep.setEnabled(false);
        mCommit.setEnabled(false);
        if (Utils.getUserLoginInfo() != null) {
            mTvPhoneNum.setText(Utils.getUserLoginInfo().getUserMobile());
            mTvPhoneNum.setEnabled(false);
        }
    }

    @OnClick({R.id.phone_check, R.id.next_step, R.id.commit, R.id.get_check_num})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.get_check_num:
                verifyMobilePhone();
                break;
            case R.id.next_step:
                String checkNum = mEtPwdCheckNum.getText().toString().trim();
                String phone = mTvPhoneNum.getText().toString().trim();
                AccountApi.verifyCode(this, phone, checkNum, new DialogCallback<Object>(this/*, getString(R.string.verifying_code)*/) {
                    @Override
                    public void onSuccess(Object o, Call call, Response response) {
                        mPhoneCheck.setVisibility(View.GONE);
                        mSetNewPwd.setVisibility(View.VISIBLE);
                        mAgainNewPwd.setVisibility(View.VISIBLE);
                        mSetInfo.setText(getString(R.string.set_pay_pwd_first));
                    }
                });

                break;
            case R.id.commit:
                String pwd = mInputPwd.getText().toString().trim();
                String pwdAgain = mAgainPwd.getText().toString().trim();
                if (CheckUtils.equalsString(pwd, pwdAgain)) {
                    if (pwd.length() == 6 && checkPwd(pwd)) {
                        PayApi.setAndForgetPayPwd(this, pwd, new DialogCallback<Object>(this/*, getString(R.string.setting_pay_pwd)*/) {
                            @Override
                            public void onSuccess(Object o, Call call, Response response) {
                                //                                XTipsDialog.showSuccess(SetPwdActivity.this, getString(R.string.set_pay_pwd_suc), () -> finish());
                                XToastUtils.showShortToast(getString(R.string.set_pay_pwd_suc));
                                finish();

                            }
                        });
                    } else {
                        XToastUtils.showShortToast(getString(R.string.pay_pwd_format));
                    }

                } else {
                    XToastUtils.showShortToast(getString(R.string.pwd_not_the_same));
                    //                    int index = mInputPwd.getSelectionStart();
                    //                    int indexAgain = mAgainPwd.getSelectionStart();
                    //                    Editable editable = mInputPwd.getText();
                    //                    Editable editableAgain = mAgainPwd.getText();
                    //                    editableAgain.delete(0, indexAgain);
                    //                    editable.delete(0, index);
                    //                    //让密码输入框获取焦点
                    //                    mInputPwd.requestFocus();
                }
                break;
        }
    }

    //验证密码必须有字母和数字组合,且为6位
    public  boolean checkPwd(String str) {
        if(CheckUtils.isEmpty(str)) {
            return false;
        } else {
            String regex = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6}$";
           return str.matches(regex);
        }
    }

    /**
     * 验证手机号
     */
    private void verifyMobilePhone() {
        final String phone = mTvPhoneNum.getText().toString().trim();
        if (CheckUtils.isEmpty(phone)) {
            XToastUtils.showShortToast(getString(R.string.msg_login_input_mobile));
        }else if(phone.length() != 11)  {
            XToastUtils.showShortToast("您输入的号码位数不正确，请输入11位数字号码");
        }else {
            if (CheckUtils.isMobilePhone(phone)) {
                mGetCheckNum.setEnabled(false);
                AccountApi.verifyCellPhone(this, 0, phone, new JsonCallback<String>(this) {

                    @Override
                    public void onSuccess(String o, Call call, Response response) {
                        if (o.equals(HttpConfig.MSG_CODE_413 + "")) {// 只有注册过的用户才会发送验证码
                            sendVerifyCode(phone);
                        } else if (o.equals(HttpConfig.MSG_CODE_412 + "")) {// 号码未注册
                            XToastUtils.showShortToast(getString(R.string.unregistered_phone));
                            mGetCheckNum.setEnabled(true);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mGetCheckNum.setEnabled(true);
                    }
                });
            } else {
                XToastUtils.showShortToast(getString(R.string.wrong_phone_number));
            }
        }
    }

    /**
     * 发送验证码请求
     */
    private void sendVerifyCode(String mobile) {

        AccountApi.sendVerifyCode(this, mobile, new JsonCallback<Object>(this) {

            @Override
            public void onSuccess(Object o, Call call, Response response) {
                XToastUtils.showShortToast(getString(R.string.send_verify_code_suc));
                mGetCheckNum.startCountDown();
            }
        });
    }


    /**
     *
     */
    private TextWatcher verifyTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mNextStep.setEnabled(mTvPhoneNum.getText().length() != 0 && mEtPwdCheckNum.getText().length() != 0);
        }
    };


    /**
     *
     */
    private TextWatcher pwdTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            mCommit.setEnabled(mInputPwd.getText().length() != 0 && mAgainPwd.getText().length() != 0);
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (verifyTextWatcher != null) {
            mTvPhoneNum.removeTextChangedListener(verifyTextWatcher);
            mEtPwdCheckNum.removeTextChangedListener(verifyTextWatcher);
            verifyTextWatcher = null;
        }
        if (pwdTextWatcher != null) {
            mInputPwd.removeTextChangedListener(pwdTextWatcher);
            mAgainPwd.removeTextChangedListener(pwdTextWatcher);
            pwdTextWatcher = null;
        }
    }
}
